package com.tgy.JUC.SampeLockDemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/***
 * @ClassName: SaleTicketsLock
 * @Description: 测试lock锁
 * @Auther: 送你一块二向箔
 * @Date: 17:28 2022/3/10
 * @version : V1.0
 */
public class SaleTicketsLock {
    public static void main(String[] args) throws InterruptedException {
        //并发：多线程操作同一个资源类，把资源丢入线程
        Tickets1 tickets = new Tickets1();
        new Thread(() -> { tickets.sale();
        }, "A").start();
        new Thread(() -> {
            tickets.sale();
        }, "B").start();
        new Thread(() -> {
            tickets.sale();
        }, "C").start();
    }
}

//资源类 oop
class Tickets1 {
    private int num = 5;
    Lock reentrantLock = new ReentrantLock();

    public void sale() {
        while (num > 0) {
            reentrantLock.lock();
            if (num<=0){
                return;
            }
            num--;
            System.out.println(Thread.currentThread().getName() + "卖出了第" + (num+1) + "张票，剩余" + num + "张票！");
            reentrantLock.unlock();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
